<template>
  <div class="waiting-purchase-wrap table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane key="" title="全部" />
      <a-tab-pane v-for="tab in Object.values(tabsMap)" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>

    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" @click="openAddPurchaseOrder" v-if="searchVal.status != 31 && $authPass('procurement.purchase.stay.placeOrder')">下采购单</a-button>
            <a-button class="gray-outline" size="medium" @click="openChooseSupplier" v-if="(!searchVal.status || searchVal.status == 20) && $authPass('procurement.purchase.stay.editSupplier')">分配供应商</a-button>
            <a-button class="gray-outline" size="medium" @click="openCutOffDialog" v-if="searchVal.status != 31 && $authPass('procurement.purchase.stay.cutoff')">截单</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="shop" title="采购计划" :width="130" fixed="left">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight">{{ record.planNo }}</p>
                    <span v-if="record.urgent" class="urgent">急</span>
                    <CopyText :val="record.planNo" class="popup-edit-icon-hover" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column data-index="salesmanName" title="销售员" :width="70" fixed="left" />
              <a-table-column data-index="purchaseDeptName" title="采购部门" :width="100" fixed="left" />
              <a-table-column data-index="shopName" title="店铺" :width="120" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :val="record.shopName" />
                </template>
              </a-table-column>
              <a-table-column data-index="img" title="图片" :width="60" fixed="left">
                <template #cell="{ record }">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column title="产品名称" :width="120">
                <template #cell="{ record }">
                  <TextLimit :val="record.productName" />
                </template>
              </a-table-column>

              <a-table-column data-index="sku" title="SKU/类目" :width="130">
                <template #cell="{ record }">
                  <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
                  <p>{{ record.cateName || '--' }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="msku" title="MSKU/ASIN" :width="130">
                <template #cell="{ record }">
                  <TextLimit :rows="1" :val="record.msku || '--'" />
                  <TextLimit :rows="1" :val="record.asin || '--'" />
                </template>
              </a-table-column>
              <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
                <template #cell="{ record }">
                  <TextLimit :val="getProductSpecs(record)" />
                </template>
              </a-table-column>
              <a-table-column title="目的仓" :width="120">
                <template #cell="{ record }">
                  <p>{{ record.warehouseName }}({{ record.warehouseCode }})</p>
                </template>
              </a-table-column>
              <a-table-column title="计划交期" :width="90">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtPlanDelivery, 'YYYY/MM/DD') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="planAmt" title="计划数量" :width="70" />
              <a-table-column data-index="purchaseStayAmt" title="待采购量" :width="70" />
              <a-table-column data-index="purchaseRealAmt" title="采购数量" :width="70" />
              <a-table-column data-index="warehouseRealAmt" title="已入库数" :width="70" />
              <a-table-column data-index="cutoffAmt" title="截单数" :width="70" />
              <a-table-column title="截单原因" :width="80">
                <template #cell="{ record }">
                  <TextLimit :val="record.cutoffMsg" />
                </template>
              </a-table-column>
              <a-table-column title="备注" :width="80">
                <template #cell="{ record }">
                  <TextLimit :val="record.remark" />
                </template>
              </a-table-column>
              <a-table-column data-index="supplierName" title="供应商" :width="100" />
              <a-table-column title="报价" :width="70">
                <template #cell="{ record }">
                  <p v-if="record.quote">已报价</p>
                  <p v-else style="color: #999">未报价</p>
                </template>
              </a-table-column>
              <a-table-column data-index="purchaseUname" title="采购负责人" :width="80" />
              <a-table-column title="采购订单号" :width="120">
                <template #cell="{ record }">
                  <TextLimit class="highlight" :val="record.purchaseNo" />
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="60" fixed="right">
                <template #cell="{ record }">
                  <a-button type="text" @click="openLogList(record)">日志</a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 截单 -->
  <CutOff v-if="showCutOffDialog" :isShow="showCutOffDialog" :list="selectRows" @closed="showCutOffDialog = false" @success="getListAndCount" />
  <!-- 分配供应商 -->
  <ChooseSupplier v-if="showChooseSupplierDialog" :isShow="showChooseSupplierDialog" :list="selectIds" @closed="showChooseSupplierDialog = false" @success="setSupplier" />
  <!-- 日志列表 -->
  <CommonLogsDialog v-if="showLogDialog" api="findPurchaseItemLogPage" :id="currentData.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message } from '@arco-design/web-vue'
  import { useRouter } from 'vue-router'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import CutOff from './components/cutOff.vue'
  import ChooseSupplier from './components/chooseSupplier.vue'
  import { findStayPurchaseItemPage, findStayPurchaseItemCountByStatus, setStayPurchaseItemSupplier } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'

  onMounted(() => {
    getWareHouseList()
    getListAndCount()
    getUserList()
    getShopList()
    getDeptList()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopIds',
      label: '店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [
        { label: '计划单号', value: 'billNos' },
        { label: 'SKU', value: 'skus' },
        { label: '产品名称', value: 'productName' },
        { label: 'MSKU', value: 'mskus' },
        { label: 'ASIN', value: 'asins' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 200,
      isMultiple: true,
    },
    {
      key: 'purchaseDeptId',
      label: '采购部门',
      placeholder: '采购部门',
      value: ref(),
      type: 'cascader1',
      width: 140,
      optionItems: [],
      attrs: {
        checkStrictly: true,
        fieldNames: { value: 'id', label: 'deptName' },
        placeholder: '采购部门',
        formatLabel: (options: any) => {
          const labels = options.map((option: any) => option.deptName)
          return labels?.[labels.length - 1]
        },
      },
    },
    {
      key: 'warehouseCode',
      label: '目的仓库',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'createUid',
      label: '创建人',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '审核日期', value: 'gmtAudit' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const tabsMap = {
    20: { key: 20, title: '待下单' },
    30: { key: 30, title: '部分下单' },
    31: { key: 31, title: '已下单' },
  }
  const countMap = ref<any>({})
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: '',
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const showCutOffDialog = ref(false)
  const showChooseSupplierDialog = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const selectRows = ref<any>([])
  const tableRef = ref()
  const router = useRouter()
  const filterData = ref<any>({})
  const tableListMap = ref({})
  const showLogDialog = ref(false)
  const currentData = ref<any>({})
  const useBaseData = useBaseDataStore()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 获取仓库列表
  async function getWareHouseList() {
    await useBaseData.getWareHouseList()
    filterItem.value[3].optionItems = useBaseData.warehouseList.map((el: any) => {
      return {
        label: el.warehouseName,
        value: el.warehouseCode,
      }
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopListAndShare()
    filterItem.value[0].optionItems = useBaseData.shopListAndShare.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[4].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 获取部门
  async function getDeptList() {
    await useBaseData.getDeptList()
    filterItem.value[2].optionItems = useBaseData.deptList
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findStayPurchaseItemCountByStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findStayPurchaseItemPage(params)
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el: any) => {
      tableListMap.value[el.id] = el
    })
  }
  // 下采购单
  function openAddPurchaseOrder() {
    if (!selectIds.value.length) {
      Message.error('请选择采购明细')
      return
    }
    let list = selectIds.value.filter((id: string) => [20, 30].includes(tableListMap.value[id]?.status))
    if (!list.length) {
      Message.error('请选择待下单或部分下单的采购明细')
      return
    }
    window.localStorage.setItem('purchaseItemIds', list.join(','))
    router.push('/purchase/purchaseManagement/addPurchaseOrder')
  }
  // 截单
  function openCutOffDialog() {
    if (!selectIds.value.length) {
      Message.error('请选择采购明细')
      return
    }
    getSelectRows()
    showCutOffDialog.value = true
  }
  // 打开选择供应商
  function openChooseSupplier() {
    if (!selectIds.value.length) {
      Message.error('请选择采购明细')
      return
    }
    let flag = selectIds.value.some((id: string) => tableListMap.value[id]?.status != 20)
    if (flag) {
      Message.error('只有待下单的明细才能分配供应商')
      return
    }
    showChooseSupplierDialog.value = true
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  // 打开日志列表
  function openLogList(row: any) {
    currentData.value = row
    showLogDialog.value = true
  }
  // 分配供货商
  async function setSupplier(supplier: any) {
    const res: any = await setStayPurchaseItemSupplier({
      ids: selectIds.value,
      supplierCode: supplier.supplierCode,
      supplierId: supplier.id,
      supplierName: supplier.supplierName,
    })
    if (res) {
      Message.success('分配成功')
      getTableList()
    }
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .urgent {
    font-size: 12px;
    background-color: red;
    color: #fff;
    width: 18px;
    border-radius: 50%;
    line-height: 18px;
    text-align: center;
    transform: scale(0.82);
  }
</style>
